package com.example.demos.service.impl;

import com.example.demos.entity.Dep;
import com.example.demos.entity.Emp;
import com.example.demos.mapper.DepMapper;
import com.example.demos.service.DepService;
import com.example.demos.util.PageBean;
import com.example.demos.util.PageParam;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigInteger;
import java.util.List;

@Service
public class DepServiceImpl implements DepService {
    @Autowired
    private DepMapper depMapper;

    @Override
    public PageBean<List<Dep>> select(PageParam pageParam, Dep dep) {
        Page<Dep> page = PageHelper.startPage(pageParam.getPage(), pageParam.getRows());
        depMapper.select(dep);
        PageBean<List<Dep>> listPageBean = new PageBean<>(page.getTotal(), page.getResult());
        return listPageBean;
    }

    @Override
    @Transactional
    public int insert(Dep dep) {
        Dep depParam = new Dep();
        List<Dep> list = depMapper.select(depParam);
        for (Dep item : list) {
            if (dep.getName().equals(item.getName())) {
                return -1;
            }
        }
        return depMapper.insert(dep);
    }

    @Override
    public Dep selectById(BigInteger id) {
        return depMapper.selectById(id);
    }

    @Override
    public int update(Dep dep) {
        List<Dep> list = depMapper.selectNotIncludeId(dep.getUuid());
        for (Dep item : list) {
            if (dep.getName().equals(item.getName())) {
                return -1;
            }
        }
        return depMapper.update(dep);
    }

    @Override
    @Transactional
    public int delete(BigInteger id) {
        List<Emp> emps = depMapper.selectEmpByDepId(id);
        if (!emps.isEmpty()) {
            return -1;
        }

        return depMapper.delete(id);
    }
}
